package ezy.lite.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;

import java.util.List;


public class ContextUtil {

    public static boolean isBackground(final Context context) {
        final ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        final List<ActivityManager.RunningAppProcessInfo> processes = manager.getRunningAppProcesses();
        for (final ActivityManager.RunningAppProcessInfo process : processes) {
            if (process.processName.equals(context.getPackageName())) {
                return process.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
            }
        }
        return false;
    }

    public static boolean isSystemApplication(Context context) {
        return context != null && isSystemApplication(context, context.getPackageName());
    }
    public static boolean isSystemApplication(Context context, String pkg) {
        return context != null && isSystemApplication(context.getPackageManager(), pkg);
    }
    public static boolean isSystemApplication(PackageManager pm, String pkg) {
        if (pm == null || pkg == null || pkg.length() == 0) {
            return false;
        }

        try {
            ApplicationInfo app = pm.getApplicationInfo(pkg, 0);
            return (app != null && (app.flags & ApplicationInfo.FLAG_SYSTEM) > 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    /** whether the app whost package's name is packageName is on the top of the stack
     * require android.permission.GET_TASKS
     */
    public static Boolean isTopActivity(Context context, String pkg) {
        if (context == null || TextUtils.isEmpty(pkg)) {
            return null;
        }

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (tasks == null || tasks.isEmpty()) {
            return null;
        }
        try {
            return pkg.equals(tasks.get(0).topActivity.getPackageName());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    public static boolean isPackageInstalled(Context context, String pkg){
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(pkg, PackageManager.GET_ACTIVITIES);
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
        return true;
    }
    /**
     * Check that in the system exists application which can handle this intent
     *
     * @param context Application context
     * @param intent  Checked intent
     * @return true if intent consumer exists, false otherwise
     */
    public static boolean isIntentAvailable(Context context, Intent intent) {
        PackageManager packageManager = context.getPackageManager();
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    public static Bundle meta(Context context) {
        try {
            return context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA).metaData;
        } catch (PackageManager.NameNotFoundException e) {
            return null;
        }
    }
    public static String meta(Context context, String key) {
        try {
            ApplicationInfo info =  context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            return info.metaData.getString(key);
        } catch (PackageManager.NameNotFoundException e) {
            return null;
        }
    }
    public static PackageInfo getPackageInfo(Context context, String pkg){
        PackageManager pm = context.getPackageManager();
        try {
            return pm.getPackageInfo(pkg, 0);
        } catch (PackageManager.NameNotFoundException e) {
        }
        return null;
    }

    public static void startActivity(Context context, Class clazz) {
        context.startActivity(new Intent(context, clazz));
    }
    public static void startActivity(Context context, Class clazz, Bundle params) {
        Intent intent = new Intent(context, clazz);
        intent.putExtras(params);
        context.startActivity(intent);
    }
    public static void startActivity(Context context, Class clazz, int flags) {
        Intent intent = new Intent(context, clazz);
        intent.setFlags(flags);
        context.startActivity(intent);
    }
    public static void startActivity(Context context, Class clazz, Bundle params, int flags) {
        Intent intent = new Intent(context, clazz);
        intent.putExtras(params);
        intent.setFlags(flags);
        context.startActivity(intent);
    }

    public static void share(Context context, String subject, String msg, String title) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        intent.putExtra(Intent.EXTRA_TEXT, msg);
        context.startActivity(Intent.createChooser(intent, title));
    }

    /**
     * 不选择，直接用系统默认浏览器打开url，在某些机型上有问题
     *
     * @param url
     * @param context
     */
    public static void openUrlByDefault(final Context context, final String url) {
        final Uri uri = Uri.parse(url);
        final Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.setData(uri);
        intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
        try {
            // 如果没有的话，至少不崩溃
            context.startActivity(intent);
        } catch (final Exception e) {
            openUrl(context, url);
        }
    }

    /**
     * 打开网页
     *
     * @param url
     * @param context
     */
    public static void openUrl(final Context context, final String url) {
        final Uri uri = Uri.parse(url);
        final Intent it = new Intent(Intent.ACTION_VIEW, uri);
        context.startActivity(it);
    }

    /**
     * 拨号
     *
     * @param num
     * @param context
     */
    public static void dail(final Context context, final String num) {
        final Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + num));
        context.startActivity(intent);
    }

    /**
     * 打电话，需要 <uses-permission id="android.permission.CALL_PHONE" />
     *
     * @param num
     * @param context
     */
    public static void call(final Context context, final String num) {
        final Uri uri = Uri.parse("tel:" + num);
        final Intent it = new Intent(Intent.ACTION_CALL, uri);
        context.startActivity(it);
    }


    /**
     * 短信
     *
     * @param to
     * @param context
     */
    public static void sms(final Context context, final String to, final String text) {
        final Intent it = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + to));
        it.putExtra("sms_body", text);
        context.startActivity(it);
    }

    /**
     * 在桌面创建一个快捷方式
     * <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
     *
     * @param act
     * @param iconResId
     * @param appnameResId
     */
    public static void createShortCut(final Activity act, final Class clz, final int iconResId, final int appnameResId) {
        // com.android.launcher.permission.INSTALL_SHORTCUT

        final Intent intent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        // 不允许重复创建
        intent.putExtra("duplicate", false);
        // 需要现实的名称
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, act.getString(appnameResId));
        // 快捷图片
        final Parcelable icon = Intent.ShortcutIconResource.fromContext(act.getApplicationContext(), iconResId);
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
        // 点击快捷图片，运行的程序主入口
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(act.getApplicationContext(), clz));
        // 发送广播
        act.sendBroadcast(intent);
    }


    /**
     * Launch a App by packageName
     *
     * @param context
     * @param packageName
     * @return
     */

    public static boolean launchApp(Context context, String packageName) {
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        if (intent != null) {
            try {
                context.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                // Acitivity Not Found
                return false;
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * Launch a App by packageName&className
     *
     * @param context
     * @param packageName
     * @return
     */

    public static boolean launchApp(Context context, String packageName, String className) {
        if (TextUtils.isEmpty(className))
            return launchApp(context, packageName);
        try {
            ComponentName cn = new ComponentName(packageName, className);
            Intent i = new Intent(Intent.ACTION_MAIN);
            i.addCategory(Intent.CATEGORY_LAUNCHER);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            i.setComponent(cn);
            context.startActivity(i);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
